package router

import (
	"bytes"
	"fmt"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/redis-client/redis_options"
	"gitee.com/zaper/service-center-client/global_sign"
	"gitee.com/zaper/service-center-client/service/discover"
	srvcerutil "gitee.com/zaper/service-center-client/util"
	reg "gitee.com/zaper/software-framework/register"
	"gitee.com/zaper/software-framework/router"
	fmkutil "gitee.com/zaper/software-framework/util"
	"gitee.com/zaper/upgradeMgr/constant"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"strings"
)

func InitializeRegister() {
	go func() {
		port := srvcerutil.GetListenPort()
		global_sign.PortChan <- port
		httpRouter := router.GetHttpRouter()
		httpRouter.RegisterRouteInstance(groups, routes, port)
		reg.InitializeRouter()
	}()
}

var groups = []string{"/api/v1/", "/api/v2"}

var routes = []router.Router{
	{groups[0], "upgrade/create", constant.HttpGET, []router.Option{create}},
	{groups[0], "upgrade/register", constant.HttpPOST, []router.Option{register}},
	{groups[0], "upgrade/register/status", constant.HttpPOST, []router.Option{registerStatus}},
}

func create(ctx *gin.Context) {
	ctx.JSON(200, "success")
}
func register(ctx *gin.Context) {
	discoveryManager := discover.GetDiscoverClientManager()
	instances := discoveryManager.GetServiceInfo("patch")
	url := fmt.Sprintf("%s%s%s", "https://", instances[0].Endpoints[0], "/api/v1/client/register")
	messageModel := "{\"process_name\":\"%s\",\"process_ip\":\"127.0.0.1\",\"process_port\":\"%s\",\"process_type\":\"java\",\"date_time\":\"%s\"}"
	upgInstances := discoveryManager.GetServiceInfo("upgradeMgr")
	endpoint := upgInstances[0].Endpoints[0]
	port := endpoint[(strings.LastIndex(endpoint, ":") + 1):]
	message := fmt.Sprintf(messageModel, "upgradeMgr", port, fmkutil.GetCurrentTime())
	options := redis_options.NewRedisOptions()
	options.Set("requestPatch", message)
	options.Close()
	client := fmkutil.NewHttpClientManager()
	resp, err := client.Post(url, "application/json", bytes.NewBuffer([]byte(message)))
	if err != nil {
		logger.Errorf("request patch fail, error is %s", err)
		fmkutil.HttpContextJSON(ctx, "fail")
		return
	}
	rt := fmkutil.HttpResponseError{}
	err = json.Unmarshal(resp, &rt)
	if err != nil {
		logger.Errorf("Unmarshal body fail, error is %s", err)
		fmkutil.HttpContextJSON(ctx, "fail")
		return
	}
	fmkutil.HttpContextJSON(ctx, rt)
}

func registerStatus(ctx *gin.Context) {
	discoveryManager := discover.GetDiscoverClientManager()
	instances := discoveryManager.GetServiceInfo("patch")
	url := fmt.Sprintf("%s%s%s", "https://", instances[0].Endpoints[0], "/api/v1/client/register/status")
	messageModel := "{\"process_name\":\"%s\",\"process_ip\":\"127.0.0.1\",\"process_port\":\"%s\",\"process_type\":\"java\",\"date_time\":\"%s\"}"
	upgInstances := discoveryManager.GetServiceInfo("upgradeMgr")
	endpoint := upgInstances[0].Endpoints[0]
	port := endpoint[(strings.LastIndex(endpoint, ":") + 1):]
	message := fmt.Sprintf(messageModel, "upgradeMgr", port, fmkutil.GetCurrentTime())
	client := fmkutil.NewHttpClientManager()
	resp, err := client.Post(url, "application/json", bytes.NewBuffer([]byte(message)))
	if err != nil {
		logger.Errorf("request patch fail, error is %s", err)
		fmkutil.HttpContextJSON(ctx, "fail")
		return
	}
	rt := fmkutil.HttpResponseError{}
	err = json.Unmarshal(resp, &rt)
	if err != nil {
		logger.Errorf("Unmarshal body fail, error is %s", err)
		fmkutil.HttpContextJSON(ctx, "fail")
		return
	}
	fmkutil.HttpContextJSON(ctx, rt)
}
